import { app, shell, BrowserWindow, ipcMain } from 'electron'
const path = require("path");
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.jpg?asset'
// 实现接受渲染进程传递过来的mac地址
ipcMain.on('getMac', (event, arg) => {
  const mac = require('getmac').default()
  console.log('我是主程序mac', mac)
  event.reply('getMac', mac)
})

function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 1920,
    height: 1080,
    show: false,
    autoHideMenuBar: true,
    icon: path.join(__dirname, '../../resources/favicon.ico'),
    webPreferences: {
      preload: path.join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(path.join(__dirname, '../renderer/src/assets/print-template.html'))
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
// 获取打印机列表的处理器
ipcMain.handle('getPrintList', async () => {
  try {
    const list = await mainWindow.webContents.getPrintersAsync();
    return list;
  } catch (error) {
    console.error('获取打印机列表失败:', error);
    return [];
  }
});
ipcMain.handle('print-order', async (event, orderData) => {
  try {
    // 创建隐藏的打印窗口
    const printWindow = new BrowserWindow({
      width: 800,
      height: 600,
      show: true,
      webPreferences: {
        nodeIntegration: true,
        contextIsolation: false
      }
    });

    // 加载打印模板
    await printWindow.loadFile(path.join(__dirname, '../renderer/print-template.html'));

    // 将订单数据发送到打印窗口
    printWindow.webContents.send('order-data', orderData);

    // 等待打印窗口准备完成
    await new Promise(resolve => {
      ipcMain.once('print-ready', async () => {
        try {
          // 获取打印机列表
          const printers = await printWindow.webContents.getPrintersAsync();
          console.log('可用打印机列表:', printers);
          const options = {
            silent: false,
            printBackground: true,
            deviceName: printers[0]?.name, // 默认使用第一个打印机
            pageSize: {
              width: 76000, // 80mm in microns
              height: 200000 // A4 height in microns
            },
            margins: {
              marginType: 'none'
            },
            scaleFactor: 100,
            copies: 1
          };

          // 执行打印
          printWindow.webContents.print(options, (success, reason) => {
            console.log('打印结果:', success ? '成功' : '失败', reason);
            // printWindow.close();
            resolve(success);
          });
          // 关闭打印窗口
          // printWindow.close();
        } catch (error) {
          console.error('打印过程出错:', error);
          // printWindow.close();
          resolve(false);
        }
      });
    });

    return true;
  } catch (error) {
    console.error('打印失败:', error);
    return false;
  }
});
